package ssw.gui.japplet;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.JOptionPane;

import ssw.game.Game;
import ssw.game.GameResults;
import ssw.game.GameState;
import ssw.game.engine.GameEngine;

public class AppCore implements ActionListener {
	private final HasContentPane top;
	
	public AppCore(HasContentPane hasContentPane)  {
		super();
		top = hasContentPane;
	}
	
	private GameEngine engine = null;

	private GameState gameState = null;

	private final IntroJPanel introPanel = new IntroJPanel(this);
	private final GameJPanel gamePanel = new GameJPanel(this);
	private final NormalRoundJPanel normalRoundPanel = new NormalRoundJPanel(this);
	
	public void initComponent()  {
		top.switchMainPanel(introPanel);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		System.out.println(event);
		
		if (event.getSource() == introPanel.btnTwoLetterWords) {
			engine = Game.create(introPanel.getGameType());
			gameState = engine.newGame();
			nextRound();
		}
	}

	private final TreeSet<String> guesses = new TreeSet<String>();
	
	public void nextRound()  {
		if (!guesses.isEmpty())  {
			gameState = engine.submit(gameState, guesses);
		}
		gamePanel.setup(gameState);

		// And Fix the GUI
		top.switchMainPanel(gamePanel);
	}
	
	public void submitGuesses(SortedSet<String> submittedGuesses) {
		guesses.clear();
		guesses.addAll(submittedGuesses);
		
		final GameResults results = GameResults.of(gameState, guesses);
		
		normalRoundPanel.setup(results);
		
		top.switchMainPanel(normalRoundPanel);
	}
}
